package com.example.demo.leetcode.top100;

import java.util.PriorityQueue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname MedianFinder
 * @description
 * @date 2023/06/27 17:17
 * <p>
 * ******************************************************
 */
public class MedianFinder {

    private PriorityQueue<Integer> small;
    private PriorityQueue<Integer> large;

    public MedianFinder() {
        small = new PriorityQueue<>();
        large = new PriorityQueue<>((a, b) -> b - a);
    }

    public void addNum(int num) {
        if (small.size() >= large.size()) {
            small.offer(num);
            large.offer(small.poll());
        } else {
            large.offer(num);
            small.offer(large.poll());
        }
    }

    public double findMedian() {
        if (small.size() > large.size()) {
            return small.peek();
        } else if (small.size() < large.size()) {
            return large.peek();
        }
        return small.isEmpty() ? 0.0 : (small.peek() + large.peek()) / 2.0;
    }

}
